package com.hitqz.robot.biz.flow.component.agv;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.common.cache.Cache;
import com.hitqz.robot.api.business.model.dto.FlowContextDto;
import com.hitqz.robot.api.business.model.dto.FlowPatrolPreAndEndTicketsDto;
import com.hitqz.robot.api.common.entity.Robot;
import com.hitqz.robot.api.dispatch.protocol.dto.RobotNextStepDto;
import com.hitqz.robot.biz.flow.util.LiteFlowUtil;
import com.hitqz.robot.biz.service.RobotMapPosService;
import com.hitqz.robot.biz.service.RobotService;
import com.hitqz.robot.driver.parent.RobotDriverService;
import com.yomahub.liteflow.annotation.LiteflowComponent;
import com.yomahub.liteflow.core.NodeComponent;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * @author xupkun
 * @date 2024/11/5
 */
@Slf4j
@LiteflowComponent(value = "PutWaitGoNextStep", name = "[轮对/轮轴]放--等待上位机可以执行下一步")
@AllArgsConstructor
public class PutWaitGoNextStep extends NodeComponent {

    private final RobotService robotService;

    private final RobotMapPosService robotMapPosService;

    private final RobotDriverService robotDriverService;

    @Override
    public void process() throws Exception {
        LiteFlowUtil.checkInterruptFlag();
        Robot robot = robotService.getDefaultRobot();
        FlowContextDto dto =  this.getRequestData();
        FlowPatrolPreAndEndTicketsDto ticketsDto = JSONObject.parseObject(dto.getTicketsTask()
                .getParseOrderParams(), FlowPatrolPreAndEndTicketsDto.class);
        String auto = ticketsDto.getModalData().get("auto")== null ? "0":
                String.valueOf(ticketsDto.getModalData().get("auto"));

        if (auto.equals("0")) {
            log.info("半自动任务:");
            return ;
        }
        Cache<String, RobotNextStepDto> nextStep = SpringUtil.getBean("nextStep");

        String targetName = ticketsDto.getModalData().get("targetPosName")== null ?
                String.valueOf(ticketsDto.getModalData().get("targetPosCode")):
                String.valueOf(ticketsDto.getModalData().get("targetPosName"));
        if (targetName.contains("LM") || targetName.equals("911020")) {
            log.info("跳过等待");
            return;
        }
        RobotNextStepDto nextDto  = nextStep.getIfPresent(robot.getRobotSn());
        log.info("放置的目标点编码:{}", targetName);
        while(true) {
            nextDto  = nextStep.getIfPresent(robot.getRobotSn());
            if (nextDto != null && targetName.equals(nextDto.getPosCode())) {
                break;
            }
            nextStep = SpringUtil.getBean("nextStep");
            TimeUnit.SECONDS.sleep(2);
            LiteFlowUtil.checkInterruptFlag();
        }
        nextDto.setPosCode("-1");
        nextStep.put(robot.getRobotSn(),  nextDto);
    }

}
